package com.jimmy.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.sql.SQLIntegrityConstraintViolationException;


@ResponseBody
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 这里的错误是
     * SQLIntegrityConstraintViolationException: Duplicate entry '110' for key 'idx_username'
     * 然后常规拼字符串操作
     * @param sqlIntegrityConstraintViolationException
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException sqlIntegrityConstraintViolationException){
           log.error(sqlIntegrityConstraintViolationException.getMessage());
           if (sqlIntegrityConstraintViolationException.getMessage().contains("Duplicate entry")){
               String[] s = sqlIntegrityConstraintViolationException.getMessage().split(" ");
               String err_msg=s[2]+"已存在";
               return R.error(err_msg);
           }
           return R.error("未知错误");
    }

    /**
     * 全局异常处理器添加CustomException
     * @param customException
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> customExceptionHanler(CustomException customException){
        log.error(customException.getMessage());
        return R.error(customException.getMessage());
    }

    @ExceptionHandler(IOException.class)
    public R<String> ioExceptionHanler(IOException ioException){
        log.error(ioException.getMessage());
        return R.error(ioException.getMessage());
    }

}
